package com.weizhong.update.util;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import com.weizhong.update.model.AppEntity;

import android.R.integer;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageDeleteObserver;
import android.content.pm.IPackageInstallObserver;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Parcelable;
import android.os.RemoteException;
import android.renderscript.Sampler.Value;
import android.util.Log;

public class AppManager {
	
	private static final String TAG = "AppManager";
	private Context mContext;
	
	public static int appCount = 0;
	
	private HashMap<String, Integer> appShortCut = new HashMap<String, Integer>();
	
	AppUpdateDetail appUpdateDetail = null;

	public AppManager(Context context) {
		// TODO Auto-generated constructor stub
		this.mContext = context;
		if(appUpdateDetail == null){
			appUpdateDetail = new AppUpdateDetail(context);
		}
	}

	/**
	 * 查询应用是否需要创建desktop
	 * @param packageName
	 * @return
	 */
	public int getShortCut(String packageName) {
		if(appShortCut != null){
			if(appShortCut.size() > 0){
				for (Entry<String, Integer> appDesk : appShortCut.entrySet()) {
					if(appDesk.getKey().equals(packageName)){
						return appDesk.getValue().intValue();
					}
				}
			}
		}
		return 0;
	}
	
	/**
	 * 设置应用是否需要创建desktop图标
	 */
	public void setShortCut(String packageName,int value) {
		if(appShortCut != null){
			appShortCut.put(packageName, value);
		}
	}

     /**
	 * 判断该应用桌面是否有快捷图标
	 * @param packageName
	 * @return
	 */
	public int hasShortCut(String packageName){
		int retValue = 0;
        boolean result = false;  
        String title = null;
        try {
            final PackageManager pm = mContext.getPackageManager();
	        try {
	        	pm.getPackageInfo(packageName, 0);

			} catch (NameNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return 0;
			}

            title = pm.getApplicationLabel(  
                    pm.getApplicationInfo(packageName,  
                            PackageManager.GET_META_DATA)).toString();  
        } catch (Exception e) { 
        	return 0;
        }
        
        if(title == null){
        	return 0;
        }
  
        final String uriStr;  
        if (android.os.Build.VERSION.SDK_INT < 8) {  
            uriStr = "content://com.android.launcher.settings/favorites?notify=true";  
		} else {  
		    uriStr = "content://com.android.launcher2.settings/favorites?notify=true";
		}
		final Uri CONTENT_URI = Uri.parse(uriStr);  
		final Cursor c = mContext.getContentResolver().query(CONTENT_URI, null,  
		        "title=?", new String[] { title }, null);  
		if (c != null && c.getCount() > 0) {  
		    result = true;  
		}

		if(result){
			retValue = 1;
		}else {
			retValue = 0;
		}
		
		return retValue;
	}
	
    /** 
     * 添加当前应用的桌面快捷方式 
     *  
     * @param cx 
     */  
    public void addShortcut(String packageName) {  
        Logger.i(TAG, "packageName: is " + packageName);
		Context context = null;
		final PackageManager pm = mContext.getPackageManager();
		try {
			context = mContext.createPackageContext(packageName,
					Context.CONTEXT_INCLUDE_CODE
							| Context.CONTEXT_IGNORE_SECURITY);
		} catch (NameNotFoundException e1) {
			// TODO Auto-generated catch block
			Log.i(TAG, "addShortcut: NameNotFoundException");
			e1.printStackTrace();
			return;
		}

		ApplicationInfo appinfo = context.getApplicationInfo();
		Drawable icon = appinfo.loadIcon(pm);
		String name = appinfo.loadLabel(pm).toString();
		Parcelable parcelable;
		try {
			parcelable = Intent.ShortcutIconResource
					.fromContext(context, appinfo.icon);
		} catch (Exception e) {
			parcelable = Intent.ShortcutIconResource
					.fromContext(context, appinfo.logo);
		}
		
		Intent shortcutIntent = pm
				.getLaunchIntentForPackage(packageName);
		Intent intent = new Intent(
				"com.android.launcher.action.INSTALL_SHORTCUT");
		intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
				shortcutIntent);
		intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
		intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
				parcelable);
		intent.putExtra("duplicate", false);
		mContext.sendBroadcast(intent);
    }
	
	public void installapp(String path,boolean force) {
		Logger.i(TAG, "install app path: " + path);
		
		Uri uri = Uri.fromFile(new File(path));
		PackageManager pm = mContext.getPackageManager();
		// 获取应用信息
		PackageInfo info = pm.getPackageArchiveInfo(path,
				PackageManager.GET_ACTIVITIES);
		long installApkVer = -1;
		//TODO:获取应用更新失败，需添加保护逻辑
		if(info == null){
			Log.e(TAG, "info is NULL!!");
			return;
		}else{
			installApkVer = info.versionCode;
		}
		//获取package name
		String packName = info.applicationInfo.packageName;
		
		int installFlags = 0;
		if (info != null) {
			installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
		}
		
		if(force){
			//强制安装
			boolean isNeedDelete = false;
			PackageInfo appinfo = null;
			try {
				appinfo = pm.getPackageInfo(packName, 0);
			} catch (NameNotFoundException e) {
				// TODO Auto-generated catch block
				Log.i(TAG,"delete packageName: " + packName + " not found,just update");
			}

			if(appinfo == null){
				Log.e(TAG, "info is NULL!!");
			}else{
				if(appinfo.versionCode != installApkVer){
					isNeedDelete = true;
				}
			}
			
			if(isNeedDelete){
				PackageDeleteObserver packageDeleteObserver = new PackageDeleteObserver();
				packageDeleteObserver.setInstallApk(true);
				packageDeleteObserver.setUri(uri);
				packageDeleteObserver.setflags(installFlags);
				packageDeleteObserver.setPackageNmae(packName);
				pm.deletePackage(packName, packageDeleteObserver, 0);
			}
		}
		
		//如果为提醒安装模式，则先判断当前应用是否正在运行
		if(appUpdateDetail.getInstallMode() == 3){
			if(!force){
				if(isAppActive(packName)){
					Log.i(TAG,packName +  "is active, 需要提醒安装");
					WindowUtils windowUtils = new WindowUtils();
					windowUtils.showPopupWindow(mContext,path,packName);
					return;
				}
			}
		}
		
		//判断当前桌面是否存在快捷方式，存在则安装后创建
		int isAddShorCut = hasShortCut(packName);

		if(isAddShorCut == 1){
			Log.i(TAG,packName + "has ShortCut");
			AppEntity appEntity = new AppEntity();
			appEntity.setPackageName(packName);
			appEntity.setIsDeskTop(1);
			if(appUpdateDetail == null){
				appUpdateDetail = new AppUpdateDetail(mContext);
			}
			appUpdateDetail.updateDesktop(appEntity);
		}

		PackageInstallObserver observer = new PackageInstallObserver();

        pm.installPackage(uri, observer, installFlags, packName);
	}
	
	class PackageInstallObserver extends IPackageInstallObserver.Stub {
		
		public void packageInstalled(String packageName, int returnCode) {
			Log.i(TAG,"packageName: " + packageName + "install complete." + " returncode: " + returnCode);
			AppEntity appEntity = new AppEntity();
			appEntity.setPackageName(packageName);
			appEntity.setUpdateSuccess(true);
			
			if(appUpdateDetail == null){
				appUpdateDetail = new AppUpdateDetail(mContext);
			}
			
			appUpdateDetail.updateUpdateResult(appEntity);

			//TODO:SHORTCUT
			if (appUpdateDetail.isAddDesktop(packageName)){
				Log.i(TAG, packageName + "添加桌面图标");
				addShortcut(packageName);
			}
		}
	}
	
	
	/** 
     * 删除当前应用的桌面快捷方式
     *  
     * @param cx 
     */  
    public void deleteShortcut(String packageName) {  
        Logger.i(TAG, "deleteShortcut: packageName: is " + packageName);
    	Log.i(TAG, "delShortcut: " + packageName);
        Intent shortcut = new Intent(  
                "com.android.launcher.action.UNINSTALL_SHORTCUT");  
        // 获取当前应用名称  
        String title = null;  
        try {  
            final PackageManager pm = mContext.getPackageManager();  
            title = pm.getApplicationLabel(  
                    pm.getApplicationInfo(packageName,  
                            PackageManager.GET_META_DATA)).toString();  
        } catch (Exception e) {
        }

        Log.i(TAG,"title: "+ title);
        // 快捷方式名称  
        try {
            Intent shortcutIntent = mContext.getPackageManager()  
                    .getLaunchIntentForPackage(packageName);

            shortcutIntent.setAction("android.intent.action.MAIN"); 

            shortcutIntent.addCategory("android.intent.category.LAUNCHER");

            shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);  

            shortcut.setPackage(null);
            shortcutIntent.setPackage(null);
            mContext.sendBroadcast(shortcut);
	} catch (Exception e) {
		e.printStackTrace();
	}
    }
	
	/**
	 * delete app
	 * @param path
	 */
	public void deleteapp(String packageName) {
		Logger.i(TAG, "delete app packageName: " + packageName);
		//删除快捷方式
		deleteShortcut(packageName);

		PackageManager pm = mContext.getPackageManager();
		// 获取应用信息
		PackageInfo info = null;
		try {
			info = pm.getPackageInfo(packageName, 0);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			Log.i(TAG,"delete packageName: " + packageName + " not found,just update");
			appCount++;
			saveUpdateAppNum(appCount);
			e.printStackTrace();
			return;
		}

		if(info == null){
			Log.e(TAG, "info is NULL!!");
			return;
		}
		//获取package name
		String packName = info.applicationInfo.packageName;
		
		PackageDeleteObserver packageDeleteObserver = new PackageDeleteObserver();
		
		pm.deletePackage(packName, packageDeleteObserver, 0);
	}

	class PackageDeleteObserver extends IPackageDeleteObserver.Stub{
		
		Uri uri = null;
		String packName;
		int installFlags = 0;
		boolean isNeedInstallApk = false;
		@Override
		public void packageDeleted(String packageName, int returnCode)
				throws RemoteException {
			// TODO Auto-generated method stub
			Log.i(TAG,"packageName: " + packageName + "delete complete. returnCode: " + returnCode);

			if(!isNeedInstallApk){
				AppEntity appEntity = new AppEntity();
				appEntity.setPackageName(packageName);
				appEntity.setUpdateSuccess(true);
				
				if(appUpdateDetail == null){
					appUpdateDetail = new AppUpdateDetail(mContext);
				}
				
				appUpdateDetail.updateUpdateResult(appEntity);
			}else{
				PackageInstallObserver observer = new PackageInstallObserver();
				PackageManager pm = mContext.getPackageManager();
				if(uri != null && packName != null){
					pm.installPackage(uri, observer, installFlags, packName);					
				}
			}
		}
		
		public void setUri(Uri uri){
			this.uri = uri;
		}
		
		public void setflags(int flags){
			installFlags = flags;
		}
		
		public void setPackageNmae(String packageName) {
			packName = packageName;
		}
		
		public void setInstallApk(boolean isInstall){
			isNeedInstallApk = isInstall;
		}
	}
	
	public void saveUpdateAppNum(int appCount){
		if(AppUpdateDetail.entity != null){
			int size = AppUpdateDetail.entity.getAppList().size();
			if(appCount > size){
				appCount = size;
			}
		}

		SharedPreferences preferences = mContext.getSharedPreferences("user",Context.MODE_PRIVATE);
		Editor editor=preferences.edit();
		editor.putInt("app_update_num", appCount);
		editor.commit();
	}
	
	public boolean isAppActive(String packageName){
		ActivityManager am = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> list = am.getRunningTasks(100);
		boolean isAppRunning = false;

		for (RunningTaskInfo info : list) {
			Log.i(TAG,"当前运行任务： " + info.topActivity.getPackageName());
			if (info.topActivity.getPackageName().equals(packageName) || info.baseActivity.getPackageName().equals(packageName)) {
				isAppRunning = true;
				Log.i(TAG,info.topActivity.getPackageName() + "info.baseActivity.getPackageName()="+info.baseActivity.getPackageName());
				break;
			}
		}

		return isAppRunning;
	}
	
	public void  removeTast(String packageName,boolean isForce) {
		Log.i(TAG,"removeTast: " + packageName);
		ActivityManager am = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);
		//List<ActivityManager.RecentTaskInfo> recentTasks = am.getRecentTasks(1,ActivityManager.RECENT_IGNORE_UNAVAILABLE);
		//recentTasks.clear();
		PackageManager mPackageManager = mContext.getPackageManager();
		
		List<ActivityManager.RecentTaskInfo> recentTasks;

		recentTasks = am.getRecentTasks(10,
				ActivityManager.RECENT_IGNORE_UNAVAILABLE);
		
		for (ActivityManager.RecentTaskInfo item : recentTasks) {
			try {
				ResolveInfo resolveInfo = mPackageManager.resolveActivity(
						item.baseIntent, 0);
				if ("com.android.systemui"
						.endsWith(resolveInfo.activityInfo.packageName)
						|| "com.android.launcher"
								.endsWith(resolveInfo.activityInfo.packageName)
						|| "com.wz.start"
								.endsWith(resolveInfo.activityInfo.packageName)
						|| "com.example.testactivityactive"
								.endsWith(resolveInfo.activityInfo.packageName)) {
					continue;
				}
				if (am != null) {
					if(resolveInfo.activityInfo.packageName.equals(packageName)){
						Log.i(TAG,"removeTast: " + resolveInfo.activityInfo.packageName);
						am.removeTask(item.persistentId,
								ActivityManager.REMOVE_TASK_KILL_PROCESS);
					}
				}
			} catch (Exception e) {
			}
		}
	}
}
